<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '基础信息' },
          { name: 'box-list', title: '用户菜单权限' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <div id="box-base" class="box-title">基础信息</div>
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <customFormItem label="角色名称" name="name" :parent="_self" :form="form" />
          <customFormItem label="角色编码" name="code" :parent="_self" :form="form" />
          <customFormItem label="是超级角色" name="isAdmin" :parent="_self" :form="form"  :type="constCommon.formItemType.switch.name"/>
          <customFormItem label="备注" name="remark" :parent="_self" :form="form"  :type="constCommon.formItemType.textarea.name" fullWidth :config="{flagValueBoolean: false}"/>
        </template>
      </customForm>

      <div id="box-list" class="box-title">用户菜单权限</div>
      <div>
        <div class="row-box-left">
          <h3>
            用户权限
            <customButton @click="saveSelect('user', '保存用户权限')" title="保存" theme="primary" size="small" help="保存用户权限"  :disabled="cpUserSaveDisabled" helpDisabled="请先保存主单局" style="float: right"/>
          </h3>
          <treeRoleUser :checkIdList="userCheckIdList" ref="treeRoleUser"></treeRoleUser>
        </div>
        <div  class="row-box-right">
          <h3>
            菜单权限
            <customButton  @click="saveSelect('menu', '保存菜单权限')" title="保存" theme="primary" size="small" help="保存菜单权限"    :disabled="cpMenuSaveDisabled" helpDisabled="请先保存主单局" style="float: right"/>
          </h3>
          <treeRoleMenu :roleId="form.id"  :checkIdList="menuCheckIdList" ref="treeRoleMenu"></treeRoleMenu>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'
import treeRoleMenu from '@/components/custom/bus/treeRoleMenu.vue'
import treeRoleUser from '@/components/custom/bus/treeRoleUser.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},

      // 所选中的用户列表
      userCheckIdList: [],
      // 所选中的菜单列表
      menuCheckIdList: []
    }
  },
  created() {
    this.$emit('event-register', {
      validate: callback => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        this.getMenuByRole()
        this.getUserByRole()
      },
      afterSave: () => {
        // 用作返回自动主键
        this.form[this.propPrimaryKey] = this.propViewFormData[
          this.propPrimaryKey
        ]
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {},
      beforeFlow: flowButtonKey => {
        return true
      },
      afterFlow: flowButtonKey => {},
      beforeClose: () => {
        return true
      }
    })
  },
  props: [
    'propPrimaryKey',
    'propDictionaries',
    'propCurrentRow',
    'propViewFormData',
    'propReadonly',
    'propStatus',
    'propRules',
    'propInitData'
  ],
  components: {customAnchor, treeRoleUser, treeRoleMenu},
  computed: {
    // 用户保存按钮是否禁用
    cpUserSaveDisabled() {
      return !this.form.id
    },
    // 菜单保存按钮是否禁用
    cpMenuSaveDisabled() {
      return !this.form.id
    }
  },
  watch: {
  },
  methods: {
    // 获取当前角色所拥有的用户
    getUserByRole() {
      if (!this.form.id) {
        this.userCheckIdList = []
        return
      }
      const url = `/roleuser/listByRoleId/${this.form.id}`
      this.$ajax.get(url, {}).then(response => {
        this.userCheckIdList = response.data.map(item => {
          return item.userId
        })
      })
    },

    // 获取当前角色所拥有的菜单
    getMenuByRole() {
      if (!this.form.id) {
        this.menuCheckIdList = []
        return
      }
      this.$ajax.get('/menu/listByRole', {
        params: {
          roleId: this.form.id
        }
      }).then(response => {
        if (response.code == 0) {
          this.menuCheckIdList = response.data.map(item => {
            return item.id
          })
        }
      })
    },

    // 保存权限操作
    saveSelect(type, msg) {
      this.utilMessage.confirm(`是否${msg}？`, () => {
        this._saveSelect(type, msg)
      })
    },

    // 保存权限操作
    _saveSelect(type, msg) {
      // 保存用户权限
      if (type == 'user') {
        let checkIdAll = this.$refs.treeRoleUser.getInst().getCheckDataList(true).filter(item => item.meta && item.meta.type &&  item.meta.type == 1).map(item2 => {
          return item2.id
        })
        let idListAdd = checkIdAll.filter(id => !this.userCheckIdList.includes(id))
        let idListDelete = this.userCheckIdList.filter(id => !checkIdAll.includes(id))
        if (idListAdd.length == 0 && idListDelete.length == 0) {
          this.utilMessage.warning('用户权限没有变化，无需保存')
          return
        }
        const params = {
          roleId: this.form.id,
          addUserIds:  idListAdd.join(','),
          deleteUserIds: idListDelete.join(',')
        }
        this.utilVue.loadShow(true)
        this.$ajax.post('/roleuser/addOrDelete', params).then(response => {
          this.utilVue.loadHide()
          if (response.code == 0) {
            this.utilMessage.success('用户权限保存成功！')
            this.userCheckIdList = checkIdAll
          }
        })
      }
      // 保存菜单权限
      if (type == 'menu') {
        let checkIdAll = this.$refs.treeRoleMenu.getInst().getCheckDataList(true).map(item2 => {
          return item2.id
        })
        let idListAdd = checkIdAll.filter(id => !this.menuCheckIdList.includes(id))
        let idListDelete = this.menuCheckIdList.filter(id => !checkIdAll.includes(id))
        if (idListAdd.length == 0 && idListDelete.length == 0) {
          this.utilMessage.warning('菜单权限没有变化，无需保存')
          return
        }
        const params = {
          roleId: this.form.id,
          addMenuIds:  idListAdd.join(','),
          deleteMenuIds: idListDelete.join(',')
        }
        this.utilVue.loadShow(true)
        this.$ajax.post('/authority/addOrDelete', params).then(response => {
          this.utilVue.loadHide()
          if (response.code == 0) {
            this.utilMessage.success('菜单权限保存成功！')
            this.menuCheckIdList = checkIdAll
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .row-box-left,.row-box-right {
    display: inline-block;
    width: 50%;
    vertical-align: top;
    padding: 0px 10px;
  }
</style>
